package accs.model.fileover;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import accs.model.AccountChecker;
import accs.model.Context;
import accs.model.ExtendedHttpClient;
import accs.model.utils.HeaderUtils;

public class FileoverChecker implements AccountChecker {

	public FileoverAccount login(String user, String password, Context ctx) throws IOException{
		
		DefaultHttpClient httpclient=new ExtendedHttpClient(ctx);
		
		List<NameValuePair> list=new ArrayList<NameValuePair>();
//		for(NameValuePair bla : list) {
//			System.out.println(bla.getName()+" -> "+bla.getValue());
//		}
		
		HttpPost post=new HttpPost("http://fileover.net/api/users/login/");
		post.setHeader(HeaderUtils.getUserAgent());
		post.setHeader(HeaderUtils.getReferer("http://fileover.net/"));
				
		
		list.add(new BasicNameValuePair("email", user));
		list.add(new BasicNameValuePair("password", password));
		post.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));

		HttpResponse resp2=httpclient.execute(post);
//		String location=resp2.getFirstHeader("Location").getValue();
		EntityUtils.consume(resp2.getEntity());
//		System.out.println(EntityUtils.toString(resp2.getEntity()));
//     	System.out.println("---------------------------------------------------------------");

		
		HttpGet get2=new HttpGet("http://fileover.net/");
		get2.setHeader(HeaderUtils.getUserAgent());
		get2.setHeader(HeaderUtils.getReferer("http://fileover.net/api/users/login/"));
		HttpResponse resp3=httpclient.execute(get2);
//		EntityUtils.consume(resp3.getEntity());
//		System.out.println(EntityUtils.toString(resp3.getEntity()));
		
		boolean valid = true;
		
		BufferedReader br=new BufferedReader(new InputStreamReader(resp3.getEntity().getContent(),"utf-8"));
		String line=null;

		while((line=br.readLine())!=null){
//			System.out.println(line);
			if(line.contains("Login")){
				valid=false;
			}
		}
		
		
		if(valid){
			return new FileoverAccount(user, password);
		}else{
			return null;
		}
	}

	public URL getImage() {
		return FileoverChecker.class.getResource("/accs/gui/img/fileover.png");
	}

	@Override
	public String getName() {
		return "fo";
	}
}
